<template>
  <div style="padding: 20px">
    <el-card>
      <div slot="header">
        <span>编辑招聘会</span>
        <el-button
          type="text"
          style="float: right; padding: 0px; margin-left: 14px"
          @click="back"
          >返回</el-button
        >
        <el-button
          type="text"
          style="float: right; padding: 0px; margin-left: 14px"
          >保存</el-button
        >
      </div>
      <div style="margin-top: 20px">
        <el-form
          ref="form"
          :model="formData"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder=""
              style="width: 30%"
            ></el-input>
            <span style="color: #999; margin-left: 10px">
              <i class="el-icon-info"></i>
              (如：2017年5月1日医药行业主题招聘会)
            </span>
          </el-form-item>
          <el-form-item label="报名时间" prop="signStartTime">
            <el-date-picker
              v-model="formData.signStartTime"
              type="datetimerange"
              align="right"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="举办时间" prop="holdStartTime">
            <el-date-picker
              v-model="formData.holdStartTime"
              type="datetimerange"
              align="right"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="主办方" prop="sponsor">
            <el-input
              v-model="formData.sponsor"
              placeholder=""
              style="width: 30%"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contacts">
            <el-input
              v-model="formData.contacts"
              placeholder=""
              style="width: 30%"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder=""
              style="width: 30%"
            ></el-input>
            <span style="color: #999; margin-left: 10px">
              <i class="el-icon-info"></i>
              (多个号码请用英文半角逗号"，"隔开)
            </span>
          </el-form-item>
          <el-form-item label="举办地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder=""
              style="width: 30%"
            ></el-input>
          </el-form-item>
          <el-form-item label="招聘会简介">
            <!-- <quillEditor />
                <quill-editor
              class="ql-editor"
              v-model="formData.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur"
              @focus="onEditorFocus"
              @change="onEditorChange"
              style="margin-top: -20px"
            >
            </quill-editor> -->
            <quill-editor
              class="ql-editor"
              v-model="formData.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur"
              @focus="onEditorFocus"
              @change="onEditorChange"
              style="margin-top: -20px"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="">
              <el-option label="线上" value="1"></el-option>
              <el-option label="线下" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="仅认证企业报名" prop="mustCompanyAudit">
            <el-switch v-model="formData.mustCompanyAudit"></el-switch>
          </el-form-item>
          <el-form-item label="要求简历完整度" prop="minCompletePercent">
            <el-input
              style="width: 30%"
              v-model="formData.minCompletePercent"
              placeholder=""
            ></el-input>
          </el-form-item>
          <el-form-item label="浏览次数" prop="click">
            <el-input
              style="width: 30%"
              v-model="formData.click"
              placeholder=""
            ></el-input>
          </el-form-item>
          <el-form-item label="联系客服" prop="qrcodeFile">
            <el-upload
              action="#"
              v-model="formData.qrcodeFile"
              :class="{ 'hide-upload': hideQrcodeUpload }"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :file-list="fileList"
              :limit="1"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传图片">
            <div class="upload-container">
              <div class="upload-item">
                <el-upload
                  action="#"
                  v-model="formData.thumbFile"
                  :class="{ 'hide-upload': hideThumbUpload }"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleThumbChange"
                  :on-remove="handleRemove"
                  :file-list="thumbFileList"
                  :limit="1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <div>
                  <div style="text-align: center">缩略图</div>
                  <div class="upload-tip">
                    <i class="el-icon-info"></i>
                    建议尺寸：240*165
                  </div>
                </div>
              </div>

              <div class="upload-item">
                <!-- <span class="upload-label">PC头图</span> -->
                <el-upload
                  action="#"
                  v-model="formData.pcHeaderLogoFile"
                  :class="{ 'hide-upload': hidePcUpload }"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handlePcHeaderChange"
                  :on-remove="handleRemove"
                  :file-list="pcHeaderFileList"
                  :limit="1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <div>
                  <div style="text-align: center">PC头图</div>
                  <div class="upload-tip">
                    <i class="el-icon-info"></i>
                    建议尺寸：1200*330
                  </div>
                </div>
              </div>

              <div class="upload-item">
                <el-upload
                  action="#"
                  v-model="formData.mobileHeaderLogoFile"
                  :class="{ 'hide-upload': hideMobileUpload }"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleMobileHeaderChange"
                  :on-remove="handleRemove"
                  :file-list="mobileHeaderFileList"
                  :limit="1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <div>
                  <div style="text-align: center">触屏头图</div>
                  <div class="upload-tip">
                    <i class="el-icon-info"></i>
                    建议尺寸：750*280
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="">
            <el-row :gutter="10">
              <el-button type="primary" @click="saveClick">保存</el-button>
              <el-button @click="back">返回</el-button>
            </el-row>
          </el-form-item>
        </el-form>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { updateJobFairApi } from "@/api/application";
// import quillEditor from "@/views/application/JobFair/participation/components/quillEditor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  // components: {
  //   quillEditor,
  // },
  data() {
    // 自定义时间校验规则
    const validateTime = (rule, value, callback) => {
      // 检查必填
      if (!value) {
        callback(new Error("时间为必填项"));
        return;
      }

      // 检查数组长度
      if (!Array.isArray(value) || value.length !== 2) {
        callback(new Error("请选择完整的时间范围"));
        return;
      }

      // 检查数组中的值是否为空
      if (!value[0] || !value[1]) {
        callback(new Error("开始时间和结束时间都必须填写"));
        return;
      }

      const startTime = value[0].getTime();
      const endTime = value[1].getTime();

      // 检查是否是有效的时间格式
      if (isNaN(startTime) || isNaN(endTime)) {
        callback(new Error("请选择有效的时间格式"));
        return;
      }

      // 检查是否是未来时间
      const now = new Date().getTime();
      // if (startTime < now) {
      //   callback(new Error("开始时间必须是未来时间"));
      //   return;
      // }

      // // 检查开始时间和结束时间
      // if (startTime >= endTime) {
      //   callback(new Error("开始时间必须小于结束时间"));
      //   return;
      // }

      callback();
    };

    return {
      model: "",
      model1: "",
      fileList: [],
      thumbFileList: [],
      pcHeaderFileList: [],
      mobileHeaderFileList: [],
      checkList: [
        // "基础会员",
        // "优选企业",
        // "专精特新小巨人",
        // "大优强/单项冠军/新能源",
        // "机关事业",
      ],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              // 直接设置value2的值
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pickerOptionss: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              // 直接设置value2的值
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },

      formData: {
        id: "",
        address: "",
        click: "",
        contacts: "",
        content: "",
        holdEndTime: "",
        holdStartTime: [], // 举办时间
        minCompletePercent: 0,
        mustCompanyAudit: true,
        phone: "",
        signEndTime: "",
        signStartTime: [], // 报名时间
        sponsor: "",
        title: "",
        type: "",
        mobileHeaderLogoFile: "",
        qrcodeSrc: "",
        pcHeaderLogoSrc: "",
        mobileHeaderLogoSrc: "",
        thumbSrc: "",
      },
      options: [
        { id: 1, name: "不使用展位/无需分配展位" },
        { id: 2, name: "北仑人才市场" },
        { id: 3, name: "宁波展览中心" },
        { id: 4, name: "通用，不分展区摊位号" },
      ],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        holdTime: [
          { required: true, message: "请选择举办时间", trigger: "change" },
          { validator: validateTime, trigger: "change" },
        ],
        signTime: [
          { required: true, message: "请选择报名时间", trigger: "change" },
          { validator: validateTime, trigger: "change" },
        ],
        sponsor: [{ required: true, message: "请输入主办方", trigger: "blur" }],
        contacts: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        address: [
          { required: true, message: "请输入举办地址", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        holdStartTime: [
          { required: true, message: "举办时间为必填项", trigger: "change" },
          { validator: validateTime, trigger: "change" },
        ],
        signStartTime: [
          { required: true, message: "报名时间为必填项", trigger: "change" },
          { validator: validateTime, trigger: "change" },
        ],
      },
      hideQrcodeUpload: false,
      hideThumbUpload: false,
      hidePcUpload: false,
      hideMobileUpload: false,
    };
  },
  mounted() {
    this.$bus.$on("editJobFair", (msg) => {
      console.log(msg);
      this.formData = msg;
      console.log(this.formData);
    });
  },
  beforeCreate() {
    this.$bus.$off("editJobFair");
  },
  created() {
    const jobFairData = JSON.parse(localStorage.getItem("editJobFair"));
    console.log("获取到的数据:", jobFairData);
    this.fileList = [{ url: jobFairData.qrcodeSrc }];
    console.log(this.fileList);

    this.thumbFileList = [{ url: jobFairData.thumbSrc }];
    this.pcHeaderFileList = [{ url: jobFairData.pcHeaderLogoSrc }];
    this.mobileHeaderFileList = [{ url: jobFairData.mobileHeaderLogoSrc }];
    console.log(this.fileList);
    if (jobFairData) {
      // 直接映射API文档要求的字段
      this.formData = {
        id: jobFairData.id,
        address: jobFairData.address,
        click: jobFairData.click,
        contacts: jobFairData.contacts, 
        content: jobFairData.content,
        minCompletePercent: Number(jobFairData.minCompletePercent),
        mustCompanyAudit: Number(jobFairData.mustCompanyAudit) === 1, // 将布尔值转换为数字
        phone: jobFairData.phone,
        sponsor: jobFairData.sponsor,
        title: jobFairData.title,
        type: jobFairData.type?.toString(),
        mobileHeaderLogoFile: jobFairData.mobileHeaderLogoFile,
        holdStartTime: [
          jobFairData.holdStartTime
            ? new Date(jobFairData.holdStartTime * 1000)
            : null,
          jobFairData.holdEndTime
            ? new Date(jobFairData.holdEndTime * 1000)
            : null,
        ],
        signStartTime: [
          jobFairData.signStartTime
            ? new Date(jobFairData.signStartTime * 1000)
            : null,
          jobFairData.signEndTime
            ? new Date(jobFairData.signEndTime * 1000)
            : null,
        ],
      };

      // 如果有二维码，处理文件列表
      // if (jobFairData.qrcodeFile) {
      //   this.fileList = [
      //     {
      //       name: "二维码",
      //       url: jobFairData.qrcodeFile,
      //     },
      //   ];
      // }
    }

    // 初始化上传按钮状态
    this.hideQrcodeUpload = this.fileList.length > 0;
    this.hideThumbUpload = this.thumbFileList.length > 0;
    this.hidePcUpload = this.pcHeaderFileList.length > 0;
    this.hideMobileUpload = this.mobileHeaderFileList.length > 0;
  },
  watch: {
    // 监听时间选择器的变化，同步到formData
    "formData.holdStartTime"(val) {
      if (val && val.length === 2) {
        this.formData.holdStartTime = val;
      }
    },
    "formData.signStartTime"(val) {
      if (val && val.length === 2) {
        this.formData.signStartTime = val;
      }
    },
  },
  methods: {
    // 自定义图片校验
    validateImage(rule, value, callback) {
      const isvalid = this.fileList.length > 0;
      console.log(isvalid);
      if (!isvalid) {
        callback(new Error("必须上传图片"));
      } else {
        callback();
      }
    },
    handleChange(file, fileList) {
      // console.log(fileList);
      this.fileList = fileList.map((item) => item);
      this.formData.qrcodeFile = fileList[0]?.raw;
      console.log(this.fileList);
      this.hideQrcodeUpload = fileList.length >= 1;
    },
    handleRemove(file, fileList) {
      // 根据删除的文件判断重置对应的显示状态
      if (this.fileList.includes(file)) {
        this.hideQrcodeUpload = false;
        this.fileList = fileList;
      } else if (this.thumbFileList.includes(file)) {
        this.hideThumbUpload = false;
        this.thumbFileList = fileList;
        this.formData.thumbFile = null;
      } else if (this.pcHeaderFileList.includes(file)) {
        this.hidePcUpload = false;
        this.pcHeaderFileList = fileList;
        this.formData.pcHeaderLogoFile = null;
      } else if (this.mobileHeaderFileList.includes(file)) {
        this.hideMobileUpload = false;
        this.mobileHeaderFileList = fileList;
        this.formData.mobileHeaderLogoFile = null;
      }
      console.log("删除文件:", file);
      console.log("当前文件列表:", fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    back() {
      this.$router.back();
    },
    // 时间戳转日期对象
    timestampToDate(timestamp) {
      if (!timestamp) return "";
      return new Date(timestamp * 1000);
    },
    // 缩略图
    handleThumbChange(file, fileList) {
      this.thumbFileList = fileList.map((item) => item);
      this.formData.thumbFile = fileList[0]?.raw;
      this.hideThumbUpload = fileList.length >= 1;
    },
    // pc头图
    handlePcHeaderChange(file, fileList) {
      this.pcHeaderFileList = fileList.map((item) => item);
      this.formData.pcHeaderLogoFile = fileList[0]?.raw;
      this.hidePcUpload = fileList.length >= 1;
    },
    // 触屏头图
    handleMobileHeaderChange(file, fileList) {
      this.mobileHeaderFileList = fileList.map((item) => item);
      this.formData.mobileHeaderLogoFile = fileList[0]?.raw;
      this.hideMobileUpload = fileList.length >= 1;
    },

    // 保存
    async saveClick() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            // 报名时间
            const startTimeMs = this.formData.holdStartTime[0].getTime();
            const endTimeMs = this.formData.holdStartTime[1].getTime();
            // 将毫秒转换为秒并取整
            const startTime = Math.floor(startTimeMs / 1000);
            const endTime = Math.floor(endTimeMs / 1000);
            // 举办时间
            const startTimeMss = this.formData.signStartTime[0].getTime();
            const endTimeMss = this.formData.signStartTime[1].getTime();
            // 将毫秒转换为秒并取整
            const startTimes = Math.floor(startTimeMss / 1000);
            const endTimes = Math.floor(endTimeMss / 1000);

            const formData = new FormData();
            formData.append("holdStartTime", startTime);
            formData.append("holdEndTime", endTime);
            formData.append("signStartTime", startTimes);
            formData.append("signEndTime", endTimes);
            // 添加其他表单数据
            formData.append("address", this.formData.address || "");
            formData.append("click", this.formData.click || "");
            formData.append("contacts", this.formData.contacts || "");
            formData.append("content", this.formData.content || "");
            formData.append(
              "minCompletePercent",
              this.formData.minCompletePercent
            );
            formData.append(
              "mustCompanyAudit",
              this.formData.mustCompanyAudit ? 1 : 0
            );
            formData.append("phone", this.formData.phone || "");
            formData.append("sponsor", this.formData.sponsor || "");
            formData.append("title", this.formData.title || "");
            formData.append("type", this.formData.type || "");
            formData.append(
              "mobileHeaderLogoFile",
              this.formData.mobileHeaderLogoFile
            );
            formData.append("pcHeaderLogoFile", this.formData.pcHeaderLogoFile);
            formData.append("thumbFile", this.formData.thumbFile);
            formData.append("qrcodeFile", this.formData.qrcodeFile);
            // 处理二维码文件
            // if (this.fileList && this.fileList.length > 0) {
            //   // 如果是新上传的文件
            //   if (this.fileList[0].raw) {
            //     formData.append("qrcodeFile", this.fileList[0].raw);
            //   }
            //   // 如果是已有的文件URL
            //   else if (this.fileList[0].url) {
            //     formData.append("qrcodeFile", this.fileList[0].url);
            //   }
            // }

            const res = await updateJobFairApi(formData, this.formData.id);
            if (res.code === 1) {
              this.$message.success("保存成功");
              this.$router.go(-1);
            } else {
              this.$message.error(res.msg || "保存失败");
            }
          } catch (error) {
            console.error("保存失败:", error);
            this.$message.error("保存失败");
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.upload-container {
  display: flex;
  flex-direction: row;
  gap: 20px;
  align-items: flex-start;
}

.upload-item {
  display: flex;
  flex-direction: column;
  align-items: content;
  gap: 5px;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  /* margin-top: 2px; */
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card) {
  display: inline-block;
}

.ql-editor {
  min-height: 400px !important;
  max-height: 560px;
  overflow-y: auto;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card) {
  display: inline-block;
}

.ql-editor {
  min-height: 400px !important;
  max-height: 560px;
  overflow-y: auto;
}

:deep(.quill-editor) {
  margin-bottom: 20px;
}

:deep(.ql-container) {
  height: 400px !important;
  font-size: 14px;
}

:deep(.ql-toolbar.ql-snow) {
  border: 1px solid #dcdfe6;
  border-bottom: none;
}

:deep(.ql-container.ql-snow) {
  border: 1px solid #dcdfe6;
}

:deep(.ql-snow .ql-tooltip[data-mode="link"]::before) {
  content: "请输入链接地址:";
}

:deep(.ql-snow .ql-tooltip.ql-editing a.ql-action::after) {
  content: "保存";
}

:deep(.ql-snow .ql-tooltip[data-mode="video"]::before) {
  content: "请输入视频地址:";
}

:deep(.ql-snow .ql-picker.ql-size .ql-picker-label::before),
:deep(.ql-snow .ql-picker.ql-size .ql-picker-item::before) {
  content: "14px";
}

.hide-upload :deep(.el-upload--picture-card) {
  display: none;
}

/* 修改这部分样式 */
/* 只对上传图片部分的容器应用居中样式 */
.upload-container :deep(.el-upload-list--picture-card) {
  display: flex;
  justify-content: center;
}

.upload-container .hide-upload {
  display: flex;
  justify-content: center;
}

/* 联系客服的上传组件保持左对齐 */
.el-form-item :deep(.el-upload-list--picture-card) {
  display: inline-block;
}

.el-form-item .hide-upload {
  display: block;
}
</style>
